package com.shanzmoo.db.store.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.shanzmoo.db.store.entity.StoreDeliveryBillDetailEntity;
import com.shanzmoo.db.store.entity.StoreDeliveryBillEntity;
import com.shanzmoo.db.store.entity.vo.StoreDeliveryBillVO;
import com.shanzmoo.db.store.entity.query.StoreDeliveryBillQuery;
import com.shanzmoo.db.store.mapper.StoreDeliveryBillMapper;
import com.shanzmoo.db.store.service.IStoreDeliveryBillDetailService;
import com.shanzmoo.db.store.service.IStoreDeliveryBillService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

/**
 * 仓库发货单 服务实现类
 *
 * @author Gzhao 2021-03-11
 */
@Service
public class StoreDeliveryBillServiceImpl extends ServiceImpl<StoreDeliveryBillMapper, StoreDeliveryBillEntity>
        implements IStoreDeliveryBillService {

    @Autowired
    private IStoreDeliveryBillDetailService storeDeliveryBillDetailService;

    @Override
    public List<StoreDeliveryBillVO> queryPageList(StoreDeliveryBillQuery query) {
        return baseMapper.queryPageList(query);
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void saveBill(StoreDeliveryBillEntity bill, List<StoreDeliveryBillDetailEntity> detailList) {
        baseMapper.insert(bill);

        detailList.forEach(e->{
            e.setBillId(bill.getId());
        });
        storeDeliveryBillDetailService.saveBatch(detailList);
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void updateBill(StoreDeliveryBillEntity bill, List<StoreDeliveryBillDetailEntity> detailList) {
        baseMapper.updateById(bill);

        StoreDeliveryBillDetailEntity detailEntity = new StoreDeliveryBillDetailEntity();
        detailEntity.setDeleted(true);

        // 删除编辑前的明细数据
        storeDeliveryBillDetailService.update(
                detailEntity,
                new QueryWrapper<StoreDeliveryBillDetailEntity>()
                        .eq("bill_id", bill.getId())
        );

        // 保存新的明细数据
        detailList.forEach(e->{
            e.setBillId(bill.getId());
        });
        storeDeliveryBillDetailService.saveBatch(detailList);
    }
}
